﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace HYFloorPipeModule
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CalculateHeat : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				UIApplication application = commandData.Application;
				UIDocument activeUIDocument = application.ActiveUIDocument;
				Document document = activeUIDocument.Document;
				Selection selection = activeUIDocument.Selection;
				HYCalculateHeatForm hycalculateHeatForm = new HYCalculateHeatForm(document, selection);
				transaction = new Transaction(document, "地热盘管散热量计算");
				transaction.Start();
				for (;;)
				{
					hycalculateHeatForm.ShowDialog();
					if (hycalculateHeatForm.DialogResult == DialogResult.Abort)
					{
						hycalculateHeatForm.GetRoomArea();
						document.Regenerate();
					}
					else
					{
						if (hycalculateHeatForm.DialogResult != DialogResult.OK)
						{
							break;
						}
						RectFloorPipe rectFloorPipe = new RectFloorPipe(application, selection, new Dictionary<string, string>
						{
							{
								"distance",
								hycalculateHeatForm.strPipeDistance
							},
							{
								"Material",
								hycalculateHeatForm.strPipeType
							}
						}, hycalculateHeatForm.roomElem as Room);
						if (hycalculateHeatForm.strType == "矩形")
						{
							rectFloorPipe.StartDraw();
						}
						else
						{
							rectFloorPipe.StartDrawYX();
						}
					}
				}
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
                    if ((int)status == 1)
					{
						transaction.Commit();
					}
                    else if ((int)status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
